package handler

import (
	"encoding/json"
	"sep23-hw/cache"
	"sep23-hw/model"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	author := c.PostForm("author")

	if title == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	content := model.Content{
		Title:  title,
		Author: author,
	}
	err := model.DB.Create(&content).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "content_add_" + strconv.Itoa(int(content.ID))
	var contents model.Content
	model.DB.Where("id=?", content.ID).First(&contents)
	jsonData, _ := json.Marshal(content)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Delete(c *gin.Context) {
	id := c.Query("id")

	var contents model.Content
	err := model.DB.Where("id=?", id).Delete(&contents).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	redis_key := "content_delete_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func Select(c *gin.Context) {
	id := c.Query("id")

	var contents model.Content

	redis_key := "content_select_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&contents)
		jsonData, _ := json.Marshal(contents)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &contents)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "搜索成功",
		"data": contents,
	})
	return
}

func List(c *gin.Context) {
	var contents []model.Content

	redis_key := "content_select_"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&contents)
		jsonData, _ := json.Marshal(contents)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &contents)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表获取成功",
		"data": contents,
	})
	return
}
